// +---------------------------------------------------------------------------+
// | 元宝系统基础JS库，公共函数															   |
// |				                                                           |
// +---------------------------------------------------------------------------+
// | Copyright (c) 2005-2010 jhfnetboy@gmail.com.  All rights reserved.        |
// | Website: http://www.yuanbao.org/                                          |
// | Author :jhfnetboy							                               |
// +---------------------------------------------------------------------------+


//截取字符串前面固定的长度，多余的已“....”代替
function getSubstr(str,len)
{
//length属性读出来的汉字长度为1
if(str.length*2 <= len)
{
   return str;
}
var strlen = 0; 
var s = "";
for(var i = 0;i < str.length; i++)
{
   if(str.charCodeAt(i) > 128)
   {   
    strlen = strlen + 2;
    if(strlen > len)
    {
     return s.substring(0,s.length-1) + "...";
    }
   }
   else
   {
    strlen = strlen + 1;
    if(strlen > len)
    {
     return s.substring(0,s.length-2) + "...";
    }
   }
  
   s = s + str.charAt(i);
  
}
return s;
}

//乘法
function accMul(arg1,arg2) 
{ 
var m=0,s1=arg1.toString(),s2=arg2.toString(); 
try{m+=s1.split(".")[1].length}catch(e){} 
try{m+=s2.split(".")[1].length}catch(e){} 
return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m) 
} 

//除法
function accDiv(arg1,arg2){ 
var t1=0,t2=0,r1,r2; 
try{t1=arg1.toString().split(".")[1].length}catch(e){} 
try{t2=arg2.toString().split(".")[1].length}catch(e){} 
with(Math){ 
r1=Number(arg1.toString().replace(".","")) 
r2=Number(arg2.toString().replace(".","")) 
return (r1/r2)*pow(10,t2-t1); 
} 
} 

//减法
function Subtr(arg1,arg2){
     var r1,r2,m,n;
     try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
     try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
     m=Math.pow(10,Math.max(r1,r2));
     //last modify by deeka
     //动态控制精度长度
     n=(r1>=r2)?r1:r2;
     return ((arg1*m-arg2*m)/m).toFixed(n);
} 
//加法
function accAdd(arg1,arg2){ 
var r1,r2,m; 
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0} 
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0} 
m=Math.pow(10,Math.max(r1,r2)) 
return (arg1*m+arg2*m)/m 
} 	

//显示指定位置id为msg的红色消息
function msg(str){
	MUI.notification('<span style="color:red;">'+str+'</span>');
	}

	//打开窗口
	function openWin(urlstr,titlestr,winid,widthx,heightx)
	{
	var myWindow2 = function(){
	new MUI.Window({
		id: winid,
		title: titlestr,
		loadMethod: 'xhr',
		contentURL: urlstr,
		width: widthx,
		height: heightx
		});
		}
		myWindow2();
	}

	function openWinhtml(urlstr,titlestr,winid,widthx,heightx)
	{
	var myWindow3 = function(){
	new MUI.Window({
		id: winid,
		title: titlestr,
		loadMethod: 'iframe',
		contentURL: urlstr,
		width: widthx,
		height: heightx
		});
		}
		myWindow3();
	}
	
function openWinhtml2(titlestr,htmlstr,winid,widthx,heightx)
	{
	var myWindow3 = function(){
	new MUI.Window({
		id: winid,
		title: titlestr,
		loadMethod: 'html',
		content: htmlstr,
		width: widthx,
		height: heightx
		});
		}
		myWindow3();
	}
	
	function operSc(a,b,c,d){//处理编码数量字符串存在则累加，否则insert，构造@--
	var loc1 = b.indexOf(a);
		if(loc1>0)
		{
		var t1 =b.substring(0,loc1);
		var t2 = b.substring(loc1);
		var loc2 = t2.indexOf('@');
		var yy1 = t2.substring(0,loc2);
		var t3 = t2.substring(loc2);
		var tt = ((yy1.split('@'))[0].split('-'))[1];
		var tx = t1+a +'-'+(parseInt(tt)+parseInt(c)).toString()+t3;
		}
		else
		{
		var tx = b+'@'+a+'-'+c+'-'+d;
		}
		return tx;
	}
	
//为菜单、图片按钮等添加更新主窗口事件
function updateMain(titlestr,urlstr,idstr){
	
	if($(idstr)!=null)
	{
    $(idstr).addEvent('click', function(e){
	new Event(e).stop();	
	MUI.updateContent({
	element: $('mainPanel'),
	url: urlstr,
	title: titlestr,
	padding: { top: 8, right: 8, bottom: 8, left: 8 }
	});
    });
    }
    else
    {	
   	MUI.updateContent({
	element: $('mainPanel'),
	url: urlstr,
	title: titlestr,
	padding: { top: 8, right: 8, bottom: 8, left: 8 }
	}); 
    }
	
 }

function freshGrid(){//读取cookie记录，显示入库记录
	if(Cookie.read('recscount')>0){for(var i =1;i<=Cookie.read('recscount');i++)
	{var trx = new  Element('tr', {id: 'tr'+i});

	var tdx0 = new  Element('td', {id: 'td0'+i});
	tdx0.innerHTML = i;	
	$(tdx0).inject(trx);
	
	var tdx1 = new  Element('td', {id: 'td1'+i});
	tdx1.innerHTML =Cookie.read('reccode'+i);	
	$(tdx1).inject(trx);
	
	var tdx2 = new  Element('td', {id: 'td2'+i});	
	tdx2.innerHTML =Cookie.read('reccount'+i);
	tdx2.inject(trx);	
	
	var tdx3 = new  Element('td', {id: 'td3'+i});
	tdx3.innerHTML =Cookie.read('recloc'+i);
	tdx3.inject(trx);	
	
	var tdx4 = new  Element('td', {id: 'td4'+i});
	tdx4.innerHTML ='img';
	tdx4.inject(trx);
	
	trx.inject('list_head_line','after');}}
}

//初始化日历的js
	window.addEvent('domready', function() {
	
	new CalendarEightysix('fromx', { 'offsetY': 14,'offsetX': -104,'format': '%Y-%m-%d' });
	
	new CalendarEightysix('tox', { 'offsetY': 14,'offsetX': -104,'format': '%Y-%m-%d'});
	});

	
	//为某个input加一个回车自动点击提交的事件
	function addEnterInput2Click(inputid,btnid){
    $(inputid).addEvent('keydown', function(event){
	 if (event.key == "enter") $(btnid).Click();
	});
	}
	
	function Tarchange(){
	//查询目标变化了，查询字段和参数界面要随之变化
	//alert($('tablex').value);
	if($('tablex').value=='product_all_info')
	{
	$('qfield').value = 'simple_code';
	$('lword').style.display = 'block';
	$('timex').style.display = "none";
	}
	if($('tablex').value=='depot_in')
	{
	$('qfield').value = 'date';
	$('lword').style.display = "none";
	$('timex').style.display = "block";
	
	}
	if($('tablex').value=='order_all_info')
	{
	$('qfield').value = 'date';
	$('lword').style.display = "none";
	$('timex').style.display = "block";
	}
	}
//query toolbar function	
function  queryUpdate(){
	var a1='',a2='',a3='',a4='',a5='',a6='',a7='',a8 ='';
	if($chk($('tablex')))
	{a1 = '?tablex='+$('tablex').value;}

	if($chk($('qfield')))
	{a2 = '&qfield='+$('qfield').value;}	

	if($chk($('swords')))
	{a3 = '&swords='+$('swords').value;}	

	if($chk($('type')))
	{a4 = '&type='+$('type').value;}	

	if($chk($('fromx')))
	{a5 = '&fromx='+$('fromx').value;}	

	if($chk($('tox')))
	{a6 = '&tox='+$('tox').value;}	

	if($chk($('like')))
	{a7 = '&like='+$('like').value;}	

	a8 = a1+a2+a3+a4+a5+a6+a7;
	var urlstr = 'index.php/Query/q'+a8;
	titlestr = 'Query Result';
	MUI.updateContent({
	element: $('mainPanel'),
	url: urlstr,
	title: titlestr,
	padding: { top: 8, right: 8, bottom: 8, left: 8 }
	});
}


var  opResult=function (data){//分析返回的json中status，ok就true，否则false
	var rt = false;
	if(data[0]['status']=='ok')
	{
	rt=true;msg(data[0]['msg']);
	return rt;	
	}
	else
	{msg(data[0]['msg'])}		
}

function fetchJsonUrl(urlstr,datastr,func){//访问指定url，返回指定格式的json
	var myRequest = new Request.JSON({
			method: 'post', 
			url: urlstr,
			headers: 'Content-Type:text/html; charset=utf-8',
			data: datastr,
			onSuccess: function(data2){
				func(data2);
			},
	
			onFailure: function(){
				msg('请求失败');
					}	
			}).send(); 
}

	
function op(str){  
	switch(str.length)
		{
		case 1:  opx(str,'num');
		break
		case 2:  opx(str,'num');
		break	
		case 3:  opx(str,'num');
		break	
		case 4:  opx(str,'num');
		break							
		case 5:  opx(str,'code');
		break
		default : msg('输入有误，请重新输入');
		break
		}
}

function opx(str,kind){//处理输入入库记录的编码
	if(($type(str.toInt())=='number') && (kind=='num'))
	{Cookie.write('nowreccount',str.toInt());msg('获得输入数量：'+str.toInt());clearme('inpt');checkin();}
//完成一次记录录入，json调用check方法，检查编码和位置码是否存在，存在则回调显示模板，显示已录入的记录，同时记录存入session，清空cookie	
	if((kind=='code'))
	{
	if($chk(Cookie.read('nowreccode')))
	{Cookie.write('nowrecloc',str);msg('获得商品位置码：'+str);clearme('inpt');checkin();}
	else
	{Cookie.write('nowreccode',str);msg('获得商品简码：'+str);clearme('inpt');checkin();}
	}
}

function checkin(){//每接收一个输入，检查一次记录是否完整
	//msg('code:'+Cookie.read('nowreccode')+',count:'+Cookie.read('nowreccount')+',loc:'+Cookie.read('nowrecloc'));
	if( $chk(Cookie.read('nowreccount')) && $chk(Cookie.read('nowreccode')) && $chk(Cookie.read('nowrecloc')) )
	{
	var urlstr ='index.php/Product/checkCL';
	var datastr = 'code='+Cookie.read('nowreccode')+'&count='+Cookie.read('nowreccount')+'&loc='+Cookie.read('nowrecloc');
	var myRequest = new Request.JSON({
			method: 'post', 
			url: urlstr,
			headers: 'Content-Type:text/html; charset=utf-8',
			data: datastr,
			onSuccess: function(data3){
				sucRec(data3);
			},	
			onFailure: function(){
				msg('请求失败,请刷新页面');	
				Cookie.dispose('nowreccode');	Cookie.dispose('nowreccount');Cookie.dispose('nowrecloc');//输入一次完成，清除本次记录cookie
					}	
			}).send(); 	
	}		
}

function sucRec(data){//验证记操作录返回的json
	if(data[0]['status']=='ok')
	{var counts = 0;
	MochaUI.notification('入库记录OK，记录了');
	if((Cookie.read('recscount')>0)) {//alert('cunzai'+Cookie.read('recscount'));
	detroytr(Cookie.read('recscount'));
	counts = parseInt(Cookie.read('recscount'))+1;}
	else{ counts = 1;}
	Cookie.write('recscount',counts);
	//alert(Cookie.read('recscount'));
	Cookie.write('reccode'+counts,Cookie.read('nowreccode'));
	Cookie.write('reccount'+counts,Cookie.read('nowreccount'));
	Cookie.write('recloc'+counts,Cookie.read('nowrecloc'));//把当前记录的cookie记录到本次入库记录
	clearNowinrec();
	//alert('sdfsdfsdfsfsdfsf');
	if($('list_head_line')) freshGrid();
	}
	else
	{
	clearNowinrec();
	MochaUI.notification('编码不存在，请重新输入');	
	}	
}

function detroytr(ct){//删除原来的旧行
for(var i =1;i<=ct;i++)
	{
	$('tr'+i).dispose();
	}	
}
function clearme(id)//清空text值
{$(id).value = '';}

//下面是入库检查库管登陆代码
function checkDpLogin(){
	if(Cookie.read('count_person'))
	{if((Cookie.read('recscount')) <1){msg('当前入库记录为空！');return false;}
	 else{return Complete();}
	}
	else
	{
		var myWindow2 = function(){
		new MUI.Window({
			id: 'aloginpage',
			title: 'ajax登陆页面',
			loadMethod: 'xhr',
			contentURL: 'index.php/Admin/ajaxLogin',
			width: 200,
			height: 150
		});
		}
		myWindow2();
	}		
}

function ajlogin(){
	//alert('ajlogin');
	var myRequest = new Request.JSON({
		method: 'post', 
		url: 'index.php/Admin/_ajaxLogin',
		headers: 'Content-Type:text/html; charset=utf-8',
		data: 'userid='+$('user_id').value+'&password='+$('password').value+'&loginKind='+$('loginKind').value,
		onSuccess: function(data){
			operate3(data);
		},
		onFailure: function(){
			$('result').set('text', '请求失败.');
				}	
		}).send();
	}
	
function operate3(data){			
		if(data[0]['status']=='ok')
		{
		$('aloginpage').dispose();
		Cookie.write('counter_person','true');
		return Complete();
		}
		else
		{MochaUI.notification('登录错误,重新输入');}
	}
//检查登陆代码结束

//下面是入库库管登陆后调用complete函数
	function Complete(){	
			var datastr ='';
			
			for(var i=1;i<=Cookie.read('recscount');i++)
			{   
				datastr = datastr+'@'+Cookie.read('reccode'+i)+'-'+ Cookie.read('reccount'+i)+'-'+Cookie.read('recloc'+i); 
			} 			
			alert('请确认已安装了Adobe Acrobat  reader，否则无法打印、阅读任何单据！');
			clearRec();
			
			var myRequest = new Request.JSON({
			method: 'post', 
			url: 'index.php/Depot/addInRec',
			headers: 'Content-Type:text/html; charset=utf-8',
			data: 'data='+datastr,
			onSuccess: function(data1){
				operate(data1);
			},	
			onFailure: function(){
				$('result').set('text', '您的请求失败了.');
					}	
			}).send(); 
		}
			
	function operate(data){		
		clearRec();//情况cookie的rec记录	
		if(data[0]['status']=='ok')
		{msg("入库记录已经建立，准备打印...");		
		updateMain('In Record Success!','index.php/Depot/In');
		var fstr = "window.open("+"'"+'index.php/Depot/printInRec?data='+data[0]['data']+"'"+");";		
		setTimeout(fstr,1000);
		}
		else
		{MochaUI.notification('输入数据有误，重新输入');}
	}
	
//complete函数结束	

//情况reccookie
function clearRec(){
	var ct = Cookie.read('recscount')
	for(var i =1;i<=ct;i++){
	Cookie.dispose('reccode'+i);	
	Cookie.dispose('recloc'+i);		
	Cookie.dispose('reccount'+i);		
	}
	Cookie.dispose('recscount');		
}

function clearNowinrec(){
Cookie.dispose('nowreccode');	Cookie.dispose('nowreccount');Cookie.dispose('nowrecloc');//输入一次完成，清除本次记录cookie	
msg('已清空本条记录缓存');}

//下单的验证记录函数
function exitSC(s,c,p)
{
	var myRequest = new Request.JSON({
			method: 'post', 
			url: 'index.php/Depot/ifexitCt',
			headers: 'Content-Type:text/html; charset=utf-8',
			data: 's='+s+'&c='+c,
			onSuccess: function(data){
				if( $chk(data))
				{
					if(data[0]['status']=='ok')
					{
						msg(data[0]['msg']);
						$('exit').click();
						addRec(s,c,p);
					}
					else
					{
						msg(data[0]['msg']);
					}					
				}
			},	
			onFailure: function(){
				msg('请求失败');
					}	
			}).send();
}

//回车响应函数，传入的是某个bt的id
function dme(event,id){
	var e = e || event;if (e.keyCode==13){;$(id).click();}	
}


//发布邀请函 TODO
function invite(){
var mail = $('invite').value;
if(IsEmail(mail))
	{
		//send mail
		msg(mail);
	}
else  msg('Not a Email');	
}


//是否为固定电话，区号3到4位，号码7到8位,区号和号码用"－"分割开，转接号码为1到6位，用小括号括起来紧跟在号码后面
function IsTelphone(str)
{
var reg=/^[0-9]{3,4}\-\d{7,8}(\(\d{1,6}\))?$/;
 return (reg.test(str));
}
//验证是否为中文
function IsChinese(str)
{
var reg=/^[\u0391-\uFFE5]+$/;
return reg.test(str);
}

//验证是否为qq号码，长度为5－10位
function IsQq(str)
{
var reg=/^[1-9]\d{4,9}$/;
return reg.test(str);
}

//验证邮编
function IsPostId(str)
{
var reg=/^\d{6}$/;
return reg.test(str);
}

//验证是否未email
function IsEmail(str)
{
var reg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; 
//var myreg = /^[-_A-Za-z0-9\.]+@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/;
return reg.test(str);
}

//手机号码验证：
function isMobel(value)    
{    
if(/^13\d{9}$/g.test(value)||(/^15[0-35-9]\d{8}$/g.test(value))||    
(/^18[05-9]\d{8}$/g.test(value))){return true;}
else{return false;}    
}
